#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from common.my_time import MyTime
from common.custom_task_data import CustomTaskData

class CustomTaskEmail():
    def __init__(self):
        self.custom_task = CustomTaskData()
        
    def __del__(self):
        pass

    def send_email(self, task_date, entity_name, start_date, custom_word, url, email, create_time, modify_time):
        if email == "bingzhao456@163.com":
            return True
        # 第三方 SMTP 服务
        mail_host="smtp.163.com"  #设置服务器
        mail_user="bingzhao456@163.com"    #用户名
        mail_pass="RINNKYNTEUUNPTLG"   #口令 
         
        mins = (modify_time - create_time).seconds // 60 + 1
        sender = 'bingzhao456@163.com'
        receivers = [email]  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        msg_body = "尊敬的用户：\n"
        msg_body += "    您好！您于" + str(task_date) + "定制的资讯，[" + entity_name + "][" + custom_word + "]已生成完成，用时[" + str(mins) + "]分钟，";
        msg_body += "浏览地址为[ http://static.saybydata.com/" + url + " ]，请注意查看。\n"
        msg_body += "    再次感谢您的支持！\n"

        message = MIMEText(msg_body, 'plain', 'utf-8')
        message['From'] = Header("bingzhao456@163.com", 'utf-8')
        message['To'] =  Header(email, 'utf-8')

        subject = 'saybydata资讯定制结果通知'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP() 
            smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
            smtpObj.login(mail_user,mail_pass)  
            smtpObj.sendmail(sender, receivers, message.as_string())
            print("邮件发送成功")
            return True
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")
            return False

    def process(self):
        tasks = self.custom_task.query_task_for_email()
        for task in tasks:
            if self.send_email(task[1], task[2], task[3], task[4], task[5], task[6], task[7], task[8]):
                self.custom_task.update_task_status(task[0], 3)
            else:
                self.custom_task.update_task_status(task[0], 4)

def custom_task_email_api():
    task = CustomTaskEmail()
    task.process()

if __name__ == '__main__':
    custom_task_email_api()
